package com.sg.framework.mq;

import com.alibaba.fastjson2.JSON;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author ：CHS
 * @since 2022/2/16 16:38
 *
 *
 * @version 1.0
 */
public class Producer {

    @Autowired(required = false)
    private DefaultMQProducer rocketMqProducer;

    /**
     * private RocketMqProperties mqProperties;
     * 发送普通消息
     *
     * @param tag
     * @param body
     * @param <T>
     * @return
     */
    public <T> boolean sendNormalMessage(String topic, String tag, T body) {

        Message message = new Message(topic, tag, JSON.toJSONBytes(body));

        try {
            SendResult sendResult = rocketMqProducer.send(message);
            return sendResult != null;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 发送普通延时消息
     *
     * @param topic
     * @param tag
     * @param body
     * @param <T>
     * @param delay 毫秒
     * @return
     */
    public <T> boolean sendNormalDelayMessage(String topic, String tag, T body, Long delay) {

        Message message = new Message(topic, tag, JSON.toJSONBytes(body));
        // 默认延时 10s
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        message.setDelayTimeLevel(3);
        try {
            SendResult sendResult = rocketMqProducer.send(message);
            return sendResult != null;
        } catch (Exception e) {
            return false;
        }
    }

}
